#include<string>
#include<vector>
#include<array>
#include<unordered_map>
#include<algorithm>
#include<limits>
#include<sstream>
#include <stack>
#include<iostream>
#define MOD 1000000007
class Solution {
public:
    std::string removeDuplicateLetters(std::string s) {
        int len = s.size();
        std::stack<int> st;
        std::array<int,26> le{};
        std::array<bool,26> b;
        b.fill(false);
        for (const char c:s)
        {
            le[c-'a']++;
        }
        for(int i=0;i<len;i++)
        {
      

            if (b[s[i]-'a'])
            {
                if (le[s[i]-'a']>0)
                {
                    le[s[i]-'a']--;
                }
             
                continue;
            }
        
            while (!st.empty()&&s[st.top()] >= s[i]&&le[s[st.top()]-'a']>0)
            {

                b[s[st.top()]-'a'] = false;
                st.pop();
              
            }
            
            if (st.empty()||s[st.top()] < s[i]&&!b[s[i]-'a'])
            {
                st.push(i);
                int ll = st.top();
                auto mm = s[st.top()]-'a';
                b[s[st.top()]-'a'] = true;
                if (le[s[i]-'a']>0)
                {
                    le[s[i]-'a']--;
                }
             
                continue;
            }
          
            if (st.empty()||s[st.top()] >= s[i]&&!b[s[i]-'a'])
            {
                std::cout<<i<<std::endl;
                std::cout<<b[s[i]-'a']<<std::endl;
                st.push(i);
                b[s[st.top()]-'a'] = true;
                if (le[s[i]-'a']>0)
                {
                    le[s[i]-'a']--;
                }
            }
        }
        int si = st.size();
        std::vector<char> ans(si);
        for (int i = si-1; i >= 0; i--)
        {
            ans[i] = s[st.top()];
            st.pop();
        }
        std::stringstream ss;
        for (int i=0;i<si;i++)
        {
            ss << ans[i];
        }
        return ss.str();
    }
};
